import { useRoute } from 'vue-router';
import { onMounted, ref } from 'vue';
import { getCategoryData } from '@/apis/Category';
import { onBeforeRouteUpdate } from 'vue-router';

export function useCategory() {
  // useRoute:拿到当前路由参数
  const route = useRoute()
  const categoryData = ref({})

  // 如果没有传就用原来的
  const getCategory = async (id = route.params.id) => {
    const res = await getCategoryData(id)
    categoryData.value = res.data.result
  }
  // to指的是当前点击的路径信息,将当前的新id传给getCategory做请求
  onBeforeRouteUpdate((to) => {
    getCategory(to.params.id)
  })

  onMounted(() => {
    getCategory()
  })

  return {
    categoryData
  }
}
